<template>
  <div class="app-container">
    <div class="search-container">
      <el-form
        v-show="showSearch"
        ref="queryParamsRef"
        :inline="true"
        :model="queryParams"
        label-width="100px"
      >
        <el-form-item label="单号" prop="applyNo">
          <el-input
            v-model="queryParams.applyNo"
            clearable
            placeholder="请输入单号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="消耗品名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入消耗品名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="是否申请" prop="isApply">
          <el-select
            v-model="queryParams.isApply"
            class="width-120"
            clearable
            placeholder="请选择是否申请"
          >
            <el-option
              v-for="dict in dictDataMap['sys_yes_no']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain type="primary" @click="handleAdd">
          <template #icon>
            <i-ep-plus/>
          </template>
          添加消耗品
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button :disabled="multiple" plain type="danger" @click="handleDelete">
          <template #icon>
            <i-ep-delete/>
          </template>
          删除
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-adaptive="55"
      :border="true"
      :data="outpTreatRecList"
      :header-cell-style="$headerCellStyle"
      :stripe="true"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column :align="'center'" type="selection" width="40"/>
      
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="单号"
        prop="applyNo"
        width="100"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        min-width="130"
        label="消耗品名称"
        prop="itemName"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="频次"
        prop="performFreqName"
        width="80"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="天数"
        prop="abidance"
        width="50"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="规格"
        prop="packageSpec"
        width="50"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="单价(元)"
        prop="price"
        width="70"
      >
        <template #default="scope">
          {{ parseFloat(scope.row.price).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="数量"
        prop="num"
        width="50"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="总价格(元)"
        prop="sumPrice"
        width="80"
      >
        <template #default="scope">
          {{ parseFloat(scope.row.sumPrice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="收费标志"
        prop="chargeFlag"
        width="90"
      >
        <template #default="scope">
          <dict-data-tag
            :options="dictDataMap['charge_flag_dict']"
            :value="scope.row.chargeFlag"
          />
        </template>
      </el-table-column>
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="开单科室"
        prop="applyDeptName"
        width="80"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="开单人"
        prop="applyDeptName"
        width="80"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="执行科室"
        prop="implementDeptName"
        width="80"
      />
      <el-table-column :align="'center'" label="确认标志" prop="confirmFlag" width="65">
        <template #default="scope">
          <dict-data-tag
            :options="dictDataMap['grant_flag']"
            :value="scope.row.confirmFlag"
          />
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="申请单" prop="isApply" width="60">
        <template #default="scope">
          <dict-data-tag
            :options="dictDataMap['sys_yes_no']"
            :value="scope.row.isApply"
          />
        </template>
      </el-table-column>
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="开单时间"
        prop="createTime"
        width="130"
      />
      <el-table-column
        :align="'center'"
        :show-overflow-tooltip="true"
        label="备注信息"
        prop="remarks"
        width="80"
      />
      <el-table-column
        :align="'left'"
        class-name="small-padding fixed-width"
        label="操作"
        width="100"
      >
        <template #default="scope">
          <el-tooltip
            v-if="scope.row.isApply === 'N'"
            class="item"
            content="打印"
            effect="dark"
            placement="left"
          >
            <el-button circle type="primary" @click="outpRecPrint(scope.row)">
              <template #icon>
                <i-ep-printer/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.isApply === 'N' && scope.row.chargeFlag === '1'"
            class="item"
            content="删除"
            effect="dark"
            placement="top"
          >
            <el-button circle type="danger" @click="handleDelete(scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改处置治疗对话框 -->
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      append-to-body
      width="500px"
      @close="cancel"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="消耗品库房" prop="implementDept">
          <el-select v-model="form.implementDept" 
                      placeholder="请输入消耗品库房" >
            <el-option v-for="materialVsDept in materialVsDeptList" :key="materialVsDept.storageId"
                        :label="materialVsDept.storageName" :value="materialVsDept.storageId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消耗品名称" prop="itemName">
          <el-input v-if="isShow" v-model="form.itemName"
                    @focus="isShowItemNameFocus()">
          </el-input>
          <automatic-completion v-else
                                ref="itemAutomatic" v-model="form.itemName"
                                :dict-array="dictArray"
                                :table-body-list="tableBodyList"
                                :table-head-list="tableHeadList"
                                :title="itemTitle"
                                :leftSpan="24" :rightSpan="0"
                                style="width: 100%" 
                                @itemNameInput="itemNameInput"
                                @row-click="rowClick"
          />
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入数量" @blur="numInput"/>
        </el-form-item>
        <el-form-item label="天数" prop="abidance">
          <el-input v-model="form.abidance" placeholder="请输入天数"/>
        </el-form-item>
        <el-form-item label="频次" prop="performFreq">
          <perform-index
            ref="performIndex"
            :placeholder="'请选择频次'"
            :value="form.performFreq"
            style="width: 100%"
            @performFreqInfoChange="performFreqInfoChange"
          />
        </el-form-item>
        <!-- <el-form-item label="执行科室" prop="implementDept">
          <base-dept-tree
            :org-id="form.orgId"
            :value="form.implementDept"
            style="width: 220px"
            @deptSelect="deptSelect"
          />
        </el-form-item> -->
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" :disabled="true" placeholder="请输入单价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="总价格" prop="sumPrice">
          <el-input v-model="form.sumPrice" :disabled="true" placeholder="请输入总价格">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <template #footer>
              <span class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitFormOk">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </span>
      </template>
    </el-dialog>

    <!-- 诊断列表弹出框 -->
    <el-dialog v-model="disOpen" :close-on-click-modal="false" :title="disTitle" append-to-body width="45%"
               @close="discancel">
      <el-divider content-position="left"><span class="divider-css">诊断信息</span></el-divider>
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="diagnosisList">
          <el-table ref="hisDiagnosisRef" :border="true" :data="hisDiagnosisList" style="margin-bottom: 28px"
                    :header-cell-style="$headerCellStyle" :stripe="true" highlight-current-row
                    @select="hisDiagnosisSelectionChange">
            <el-table-column :align="'center'" type="selection" width="40"/>
            <el-table-column :align="'center'" label="西/中医诊断" prop="type">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['chinese_western_type']" :value="scope.row.type"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="诊断类型" prop="diagnosisType" width="110px">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['diagnosis_type']"
                               :value="scope.row.diagnosisType"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                             width="150px"/>
            <el-table-column :align="'center'" label="诊断编码" prop="icdCode"/>
            <!--            <el-table-column :align="'center'" label="效果" prop="effect">-->
            <!--              <template #default="scope">-->
            <!--                <dict-data-tag :options="dictDataMap['treatment_type']" :value="scope.row.effect"/>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column :align="'center'" label="诊断医生" prop="diagnosisDoctorName" width="100"/>
          </el-table>
        </el-form-item>

      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="disdialogOk">确 定</el-button>
                    <el-button @click="discancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "MaterialOutTre",
};
</script>

<script setup lang="ts">
import {
  addRecMaterial,  
  selectPageOutpTreatRec,
  ergodicDeleteBo,
} from "@/api/clinicOrder/outpTreatRec";

import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";
import {jsonStrInObj, materialExportList} from "@/utils/autoComplete";
import { autoExportList } from "@/api/material/materialStock"; 
import {idNo, positiveNumber} from "@/utils/myRules";
import {listHisDiagnosis} from "@/api/diagnosis/hisDiagnosis.ts";
import {getMaterialVsDeptList} from "@/api/material/materialStorageDept.ts"

const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "clinic_or_visit",
    "charge_flag_dict", 
    "sys_yes_no","chinese_western_type",
    'diagnosis_type', 'grant_flag'
  )
);

// 项目选择自动补全窗体名称
const itemTitle = ref("选择耗材");
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(materialExportList));
// 项目选择自动补全表格数据
const tableBodyList = ref([]);
// 项目选择自动补全字典数组
const dictArray = ref(["bill_item_class_dict"]);

const itemAutomatic = ref();
const props = defineProps({
  inoroutFlag: {
    type: String,
    default: "",
  },
  // 是否来在OTC门诊   ，用于判断是否弹出诊断选择框
  isOtcOutpatient: {
    type: Boolean,
    default: true
  }
});
const clinicId = ref(proxy.$clinicId);
const patientId = ref(proxy.$patientId);
const formRef = ref();
const queryParamsRef = ref();
const outpTreatRecList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectionAny = ref<any>([]);
// 消耗品库房list
const materialVsDeptList = ref<any>([])
const form = ref<any>({
  id: "",
  clinicId: clinicId.value,
  clinicOrdersId: "",
  patientId: patientId.value,
  inoroutFlag: props.inoroutFlag,
  confirmFlag: "N",
  chargeFlag: "1",
  stockId: "",
  groupNo: "",
  applyNo: "",
  abidance: 1,
  applyUser: userInfo.userId,
  implementDept: "",
  applyDept: userInfo.loginDeptId,
  performFreq: "",
  itemName: "",
  num: 1,
  orgId: userInfo.orgId,
  remarks: "",
  isApply: "N",
  isPhy: "N",
  itemClass: "",
  unitsStr: "",
  supplierName: "",
  packageSpec: "",
  isClinicFee: "",
  mark: "",
  clinicItemName: "",
  itemInfo: "",
  isFiltrationContrastExist: true,
  // 是否附带费用 true：是   false：否
  whetherToComeInAttached: false,
  hisDiagnosisList: {},
  icdCode: "",
  icdName: ""
});
const autoForm = ref<any>({
  clinicItemName: "",
  itemInfo: "",
  orgId: userInfo.orgId,
  storageId: "",
  isFiltrationContrastExist: true,
  notInSelect: [],
});
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  clinicId: "",
  clinicOrdersId: "",
  patientId: "",
  inoroutFlag: "",
  confirmFlag: "",
  chargeFlag: "",
  stockId: "",
  groupNo: "",
  applyNo: "",
  implementDept: "",
  applyDept: "",
  orgId: userInfo.orgId,
  remarks: "",
  isApply: "",
});
//处置治疗增加诊断
const disOpen = ref(false);
const disTitle = ref("添加诊断信息");
const diagnosIds = ref([""]);
const hisDiagnosisRef = ref()
// 诊断列表
const hisDiagnosisList = ref<any>([])

const rules = ref<any>({
  itemName: [{required: true, message: "项目不能为空", trigger: "change"}],
  implementDept: [{required: true, message: "执行科室不能为空", trigger: "change"}],
  num: [{required: true, validator: positiveNumber, trigger: "blur"}],
  abidance: [{required: true, validator: positiveNumber, trigger: "blur"}],
});

const dialogFormRef = ref()
const dialogForm = ref<any>({
  diagnosisList: ''
})

const dialogRules = ref<any>({
    diagnosisList: [
      {required: true, message: "请先开具诊断或者选择至少一条诊断后，再保存", trigger: "change"}
    ]
  }
)

/** 查询处置治疗列表 */
function getList() {
  queryParams.value.clinicId = clinicId.value;
  queryParams.value.patientId = patientId.value;
  queryParams.value.itemClass = 'I';
  selectPageOutpTreatRec(queryParams.value).then((response: any) => {
    outpTreatRecList.value = response.rows;
    total.value = response.total;
  });
}

/** 项目列表行点击事件 */
function rowClick(row: any) {
  itemAutomatic.value.closePopover(); 
  isShow.value = true
  console.log(row);
  
  form.value.clinicItemId = row.materialPriceId;
  form.value.stockId = row.stockId;
  form.value.itemName = row.materialName;
  form.value.itemCode = row.materialCode;
  form.value.itemClass = 'I';
  form.value.itemSpec = row.currentSpec;
  form.value.supplierName = row.firmName;
  autoForm.value.clinicItemName = row.materialName;
  const subTotal = Number(row.retailPrice) ? Number(row.retailPrice) : 0;
  form.value.price = subTotal.toFixed(2);
  form.value.tradePrice = row.purchasePrice;
  form.value.packageSpec = row.packageSpec;
  form.value.unitsStr = row.packSize==='1' ? row.minUnitsName:row.packageUnitsName;
  form.value.sumPrice = (subTotal * form.value.num).toFixed(2);
  tableBodyList.value = [];
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.itemName)
    itemAutomatic.value.focusInput()
  })
}

/** 项目名称自动补全检索 */
function itemNameInput(itemName: String) {
  autoForm.value.itemInfo = itemName;
  getListMaterial();
}

/** 默认频次选择事件 */
function performFreqInfoChange(obj: any) {
  form.value.performFreq = obj.freqId;
}

function deptSelect(node: any) {
  form.value.implementDept = node.deptId;
  // form.value.deptName = node.deptName
}

/** 自动补全后台查询 */
function getListMaterial() {
  if (autoForm.value.itemInfo) { 
    autoForm.value.orgId = userInfo.orgId; 
    autoForm.value.storageId = form.value.implementDept;
    console.log(autoForm.value);
    
    autoExportList(autoForm.value).then((res) => {
      tableBodyList.value = res.data;
      // 打开自动补全弹出框
      itemAutomatic.value.init();
    });
  } else {
    tableBodyList.value = [];
  }
}

/** 数量改变事件 */
function numInput() {
  form.value.sumPrice = (form.value.price * form.value.num).toFixed(2);
}

// 取消按钮
function cancel() {
  reset();
  open.value = false;
}

// 表单重置
function reset() {
  form.value = {
    clinicId: clinicId.value,
    clinicOrdersId: "",
    patientId: patientId.value,
    inoroutFlag: props.inoroutFlag,
    confirmFlag: "N",
    chargeFlag: "1",
    stockId: "",
    groupNo: "",
    applyNo: "",
    abidance: 1,
    applyUser: userInfo.userId,
    implementDept: "",
    applyDept: userInfo.loginDeptId,
    performFreq: "",
    itemName: "",
    num: 1,
    orgId: userInfo.orgId,
    remarks: "",
    itemClass: "",
    unitsStr: "",
    supplierName: "",
    packageSpec: "",
    isApply: "N",
    isPhy: "N",
    // 是否附带费用 true：是   false：否
    whetherToComeInAttached: false,
    hisDiagnosisList: {},
    icdCode: "",
    icdName: ""
  };
  // nextTick(() => {
  //     formRef.value.resetFields()
  // })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: any) {
  selectionAny.value = selection;
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构");
  }
  open.value = true;
  reset();
  // form.value.implementDept = userInfo.loginDeptId
  title.value = "添加消耗品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  form.value = row;
  title.value = "修改消耗品";
  nextTick(() => {
    itemAutomatic.value.setItemName(row.itemName);
  });
}

/** 提交按钮 */
function submitForm() {
  buttonLoading.value = true;
  if (form.value.id != null) {
     
  } else {
    addRecMaterial(form.value)
      .then(() => {
        ElMessage.success("新增成功");
        disOpen.value = false;
        dialogForm.value.diagnosisList = [];
        diagnosIds.value = []
        open.value = false;
        getList();
        reset();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  }

}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  let type = true;
  for (let i: number = 0; i < selectionAny.value.length; i++) {
    let index = outpTreatRecList.value.findIndex((item: any) => {
      return item.id === selectionAny.value[i].id;
    });
    type = deleteAndEditValid(selectionAny.value[i], index + 1);
    if (!type) {
      break;
    }
  }
  if (type) {
    ElMessageBox.confirm("是否确认删除消耗品？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        ergodicDeleteBo(_ids).then(() => {
          getList();
          ElMessage.success("删除成功");
        });
      })
      .catch(() => {
      });
  }
}

/**
 * 删除或者修改校验
 * @ param row
 * @ param index 行数
 */
function deleteAndEditValid(row: any, index: number) {
  if (row.chargeFlag === "2") {
    ElMessage.error("第" + index + "行项目状态：已收费，");
    return false;
  } else if (row.chargeFlag === "3") {
    ElMessage.error("第" + index + "行项目状态：申请退费");
    return false;
  } else if (row.chargeFlag === "4") {
    ElMessage.error("第" + index + "行项目状态：已退费");
    return false;
  } else if (row.chargeFlag === "5") {
    ElMessage.error("第" + index + "行项目状态：确认退费");
    return false;
  } else if (row.chargeFlag === "6") {
    ElMessage.error("第" + index + "行项目状态：科室确认退费中");
    return false;
  } else {
    return true;
  }
}

/**
 * 打印
 */
function outpRecPrint(row) {
  let url = "/business/outpTreatRec/outpRecPrint";
  const formData = new FormData()
  const idArr = row.id || ids.value.join()
  formData.append("idStr", idArr)
  formData.append("orgId", userInfo.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      // objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('打印失败')
    }
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/outpTreatRec/export",
    {
      ...queryParams.value,
    },
    `outpTreatRec_${new Date().getTime()}.xlsx`
  );
}

/**
 * 检验通过，弹出诊断选择狂
 * 校验通过后，由处方明细组件emits调用
 */
function openTrue() {
  disOpen.value = true
  hisDiagnosisList.value.forEach((item: any) => {
    nextTick(() => {
      hisDiagnosisRef.value.toggleRowSelection(item, false);
    })
  })
  const index = hisDiagnosisList.value.findIndex((item: any) => {
    return item.id === ids.value[0]
  })
  if (index > -1) {
    nextTick(() => {
      //让页面显示选中的数据
      hisDiagnosisRef.value.toggleRowSelection(hisDiagnosisList.value[index], true);
    })
  }
}

/**
 * 关闭诊断弹出框
 */
function discancel() {
  disOpen.value = false
}

/**
 * 诊断弹出框确认按钮
 */
function submitFormOk() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      if (props.isOtcOutpatient === true) {
        submitForm()
      } else {
        openTrue()
      }
    }
  });
}

function disdialogOk() {
  (dialogFormRef.value as any).validate(valid => {
    if (valid) {
      form.value.diagnosisList = dialogForm.value.diagnosisList
      form.value.icdCode = dialogForm.value.diagnosisList.icdCode
      form.value.icdName = dialogForm.value.diagnosisList.icdName
      submitForm()
    }
  })
}

/**
 * 诊断单选
 * @param selection
 */
function hisDiagnosisSelectionChange(selection: any) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    hisDiagnosisRef.value.toggleRowSelection(del_row, false);
  }
  diagnosIds.value = selection.map(item => item.id);
  const index = hisDiagnosisList.value.findIndex(item => {
    return item.id === diagnosIds.value[0]
  })
  if (index > -1) {
    dialogForm.value.diagnosisList = hisDiagnosisList.value[index]
  }

}

/** 查询患者诊断表列表 */
function getDiagnosisList() {
  const form = {
    patientId: patientId.value,
    clinicId: clinicId.value
  }
  listHisDiagnosis(form).then((response: any) => {
    hisDiagnosisList.value = response.data;
  });
}

// 以科室id查询对应的药房、药库信息
function getMaterialVsDeptListFun() {
  let data = {
    deptId: userInfo.loginDeptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("4,2,0", ","),
    storageTypeArray: proxy.$stringToArray("2,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("1", ","),
  }
  getMaterialVsDeptList(data).then((res: any) => {
    materialVsDeptList.value = res.data 
     
  })
}

getList();
getDiagnosisList();
getMaterialVsDeptListFun();
defineExpose({
  getList
})
</script>

<style scoped>
.app-container {
  padding: 0px !important;
}
</style>
